package com.ljl.ningwei.common.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljl.ningwei.common.exception.ClientException;
import com.ljl.ningwei.common.utils.JWTUtil;
import com.ljl.ningwei.dto.UserInfoDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

public class JWTIntercepter implements HandlerInterceptor {
    public static final Logger LOGGER = LoggerFactory.getLogger(JWTIntercepter.class);
    /**
     * 添加用户身份认证
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String jwttoken = request.getHeader("token");
        if (jwttoken == null || jwttoken.isEmpty()) {
            throw new ClientException("用户请重新登录");
        }
        try {
            Claims claims = JWTUtil.parseJWT(jwttoken);
            String subject = claims.getSubject();
            ObjectMapper objectMapper = new ObjectMapper();
            UserInfoDTO userInfoDTO = objectMapper.readValue(subject, UserInfoDTO.class);
            LOGGER.info("usInfoDTO:{}",userInfoDTO);
        } catch (Exception e) {
            LOGGER.info("JWT解析异常:" + e.getMessage());
            throw new ClientException("token认证失效请重新登录");
        }
        return true;
    }
}
